package com.guopiao.vat.common.util;

import org.apache.commons.lang3.StringUtils;
import org.joda.time.DateTime;
import org.joda.time.Period;
import org.joda.time.PeriodType;

import javax.xml.datatype.DatatypeFactory;
import javax.xml.datatype.XMLGregorianCalendar;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.ParsePosition;
import java.text.SimpleDateFormat;
import java.util.*;

public class DateTimeUtil {

  /**
   * 通过传过来的日期获取日期中为第几月份
   *
   * @param date 传过来的日期
   */
  public static int getMonthForDate(Date date) {
    Calendar calender = Calendar.getInstance();
    calender.setTime(date);
    return calender.get(Calendar.MONTH) + 1;
  }

  /**
   * 获取当前年
   */
  public static int getYearForDate() {
    Calendar calender = Calendar.getInstance();
    return calender.get(Calendar.YEAR);
  }

  /***
   * 将string类型的字符串转换成指定格式的Date
   *
   * @param dateStr
   *            字符串
   * @param pattern
   *            转换格式
   * @return
   */
  public static Date getStringToDate(String dateStr, String pattern) {
    if (StringUtils.isBlank(dateStr) || StringUtils.isBlank(pattern)) {
      return null;
    }
    try {
      DateFormat dateformat = new SimpleDateFormat(pattern);
      return dateformat.parse(dateStr);

    } catch (ParseException e) {
      e.printStackTrace();
    }
    return null;
  }

  /**
   * 将时间转换成指定格式的字符串
   */
  public static String getDateToString(Date date, String pattern) {
    if (date == null || StringUtils.isBlank(pattern)) {
      return null;
    }
    DateFormat dateformat = new SimpleDateFormat(pattern);
    return dateformat.format(date);
  }

  /**
   * 日期转换为yyyy-MM-DD 的字符串
   */
  public static String getyyyy_MM_DD(Date date) {
    if (date == null) {
      return null;
    }
    DateFormat dateformat = new SimpleDateFormat("yyyy-MM-dd");
    return dateformat.format(date);
  }

  /**
   * 日期转换为yyyyMMdd 的字符串
   */
  public static String getyyyyMMDD(Date date) {
    if (date == null) {
      return null;
    }
    DateFormat dateformat = new SimpleDateFormat("yyyyMMdd");
    return dateformat.format(date);
  }

  /**
   * 日期转换为MM/dd/yyyy 的字符串
   */
  public static String getMM_DD_YYYY(Date date) {
    if (date == null) {
      return null;
    }
    DateFormat dateformat = new SimpleDateFormat("MM/dd/yyyy");
    return dateformat.format(date);
  }

  // 获取当前时间的前一年或者前一月或者钱一周的时间
  // Calendar.YEAR
  // Calendar.MONTH
  public static Date getQian(int type, int time) {
    Calendar calendar = Calendar.getInstance();
    Date date = new Date(System.currentTimeMillis());
    calendar.setTime(date);
    calendar.add(type, time);
    date = calendar.getTime();
    return date;
  }

  /**
   * 获取yyyy-MM-dd HH:mm:ss时间格式的字符串
   */
  public static String getYYYYMMddHHmmss(Date date) {
    if (date == null) {
      return null;
    }
    DateFormat dateformat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    return dateformat.format(date);
  }

  /**
   * 获取yyyy-MM-dd HH-mm-ss时间格式的字符串
   */
  public static String getNewYYYYMMddHHmmss(Date date) {
    if (date == null) {
      return null;
    }
    DateFormat dateformat = new SimpleDateFormat("yyyy-MM-dd HH-mm-ss");
    return dateformat.format(date);
  }

  /**
   * @return 返回时间格式YYYYMMddHHmmss
   */

  public static String getStringDateYYYYMMddHHmmss(Date date) {
    if (date == null) {
      return null;
    }

    SimpleDateFormat dateformat = new SimpleDateFormat("yyyyMMddHHmmss");
    return dateformat.format(date);
  }

  /**
   * @return 返回时间格式YYYYMMddHHmmss
   */

  public static String getYYYYMMddHHmmss() {
    SimpleDateFormat dateformat = new SimpleDateFormat("yyyyMMddHHmmss");
    return dateformat.format(new Date());
  }

  public static String HHmm() {
    SimpleDateFormat dateformat = new SimpleDateFormat("HHmm");
    return dateformat.format(new Date());
  }

  public static String HHmmss() {
    SimpleDateFormat dateformat = new SimpleDateFormat("HHmmss");
    return dateformat.format(new Date());
  }

  /**
   * @return 返回时间格式HH:mm
   */

  public static String getStringDateHH_mm(Date date) {
    if (date == null) {
      return null;
    }

    SimpleDateFormat dateformat = new SimpleDateFormat("HH:mm");
    return dateformat.format(date);
  }

  /**
   * @return 返回时间格式HH:mm
   */

  public static String getStringDateHHmmss(Date date) {
    if (date == null) {
      return null;
    }

    SimpleDateFormat dateformat = new SimpleDateFormat("HHmmss");
    return dateformat.format(date);
  }

  /**
   * 功能描述：根据传入的日期得到是星期几 1---星期一 2---星期二 3---星期三 4---星期四 5---星期五 6---星期六
   * 7---星期日
   */
  public static int getDayOfWeek(Date date) {
    Calendar calendar = Calendar.getInstance();
    calendar.setTime(date);

    int dayOfWeek = calendar.get(Calendar.DAY_OF_WEEK);
    dayOfWeek--;
    if (dayOfWeek == 0) {
      dayOfWeek = 7;
    }

    return dayOfWeek;
  }

  /**
   * 使用参数Format将字符串转为pattern格式的Date ,区分是否包含时分秒，不是pattern格式的字符串
   */
  public static Date dateParse(String strDate, String pattern) {
    if (StringUtils.isBlank(strDate) || StringUtils.isBlank(pattern)) {
      return null;
    }

    try {
      DateFormat dateformat = new SimpleDateFormat(pattern);
      return dateformat.parse(strDate);

    } catch (ParseException e) {
      e.printStackTrace();
    }

    return null;
  }

  /**
   * 只有年月日的时间
   */
  public static Date dateParseyyyyMMDD(String strDate) {
    return dateParse(strDate, "yyyy-MM-dd");
  }

  /**
   * 包含年月日 时分秒
   */
  public static Date dateParseyyyyMMDDHHmmss(String strDate) {
    return dateParse(strDate, "yyyy-MM-dd HH:mm:ss");
  }

  /**
   * 包含年月日 时
   */
  public static Date dateParseyyyyMMDDHH(String strDate) {
    return dateParse(strDate, "yyyy-MM-dd HH");
  }

  /**
   * 增加或减少多少年（或月，日）后日期
   */
  public static Date addOrMinusDate(Date nowdate, int delay, int yearOrmonthOrDay) {
    Calendar calendar = Calendar.getInstance();
    calendar.setTime(nowdate);
    calendar.add(yearOrmonthOrDay, delay);
    Date date = calendar.getTime();
    return date;
  }

  /**
   * 增加或减少多少年后的日期
   */
  public static Date addOrMinusYear(Date nowdate, int delay) {
    return addOrMinusDate(nowdate, delay, Calendar.YEAR);
  }

  /**
   * 增加或减少多少月后的日期
   */
  public static Date addOrMinusMonth(Date nowdate, int delay) {
    return addOrMinusDate(nowdate, delay, Calendar.MONTH);
  }

  /**
   * 增加或减少多少日后的日期
   */
  public static Date addOrMinusDay(Date nowdate, int delay) {
    return addOrMinusDate(nowdate, delay, Calendar.DAY_OF_YEAR);
  }

  /**
   * 增加或减少多少小时后的日期
   */
  public static Date addOrMinusHour(Date nowdate, int delay) {
    return addOrMinusDate(nowdate, delay, Calendar.HOUR);
  }

  /**
   * 增加或减少多少分钟后的日期
   */
  public static Date addOrMinusMinute(Date nowdate, int delay) {
    return addOrMinusDate(nowdate, delay, Calendar.MINUTE);
  }

  /**
   * 两个日期之间相隔天数
   */
  public static double daysBetween(Date startDate, Date endDate) {
    Double a = Double.valueOf(endDate.getTime());
    Double b = Double.valueOf(startDate.getTime());
    Double diff = Math.abs(a- b);
    diff = Math.ceil(diff / (3600 * 1000 * 24));
    return diff;
  }

  /**
   * 两个日期之间相隔分钟
   */
  public static long minutesBetween(Date startDate, Date endDate) {
    long diff = Math.abs(endDate.getTime() - startDate.getTime());
    diff = diff / (60 * 1000);

    return diff;
  }

  /**
   * 两个日期之间相隔秒数
   */
  public static long secondsBetween(Date startDate, Date endDate) {
    long diff = Math.abs(endDate.getTime() - startDate.getTime());
    diff = diff / 1000;

    return diff;
  }

  /**
   * 〈功能详细描述〉获得时间的时分
   *
   * @since 企业商旅v1.0.0
   */
  public static String getHourAndMinutes(String strDate) {
    Date date = dateParse(strDate, "yyyy-MM-dd HH:mm:ss");
    SimpleDateFormat format = new SimpleDateFormat("HH:mm");
    String returnStr = format.format(date);
    return returnStr;

  }

  /**
   * 〈功能详细描述〉根据字符串获得日期yyyy-MM-dd
   *
   * @param strDate :strDate参数格式yyyy -MM-dd HH:mm:ss
   * @since 企业商旅v1.0.0
   */
  public static String getDate(String strDate) {
    Date date = dateParse(strDate, "yyyy-MM-dd HH:mm:ss");
    return getyyyy_MM_DD(date);
  }

  /**
   * 年月日按照 yyyyMMdd 格式转成日期
   */
  public static Date stryyyyMMddToDate(String strDate) {
    return dateParse(strDate, "yyyyMMdd");
  }

  /**
   * 日期转换为yyyy-MM-DD 的字符串
   */
  public static String getyyyyMMdd(Date date) {
    if (date == null) {
      return null;
    }
    DateFormat dateformat = new SimpleDateFormat("yyyyMMdd");
    return dateformat.format(date);
  }

  /**
   * 日期转换为yyyy年MM月DD日 的字符串
   */
  public static String getFormat(Date date) {
    return getFormat(date, "yyyy年MM月dd日");
  }

  /**
   * 日期转换
   */
  public static String getFormat(Date date, String pattern) {
    if (date == null) {
      return null;
    }
    DateFormat dateformat = new SimpleDateFormat(pattern);
    return dateformat.format(date);
  }

  /**
   * 〈功能详细描述〉获取某月的第一天
   *
   * @since 企业商旅v1.0.0
   */
  public static Date getDateByMonth(int year, int month, String day) {
    Calendar calendar = Calendar.getInstance();
    calendar.set(Calendar.YEAR, year);
    calendar.set(Calendar.MONTH, month - 1);
    if (day.equals("0")) {// 获取第一天
      calendar.set(Calendar.DAY_OF_MONTH, calendar.getMinimum(Calendar.DATE));
    } else {// 获取最后一天
      calendar.set(Calendar.DAY_OF_MONTH, calendar.getActualMaximum(Calendar.DATE));
    }
    // calendar获取日期的格式为：yyyy-MM-dd HH:mm:ss
    return dateParseyyyyMMDD(getyyyy_MM_DD(calendar.getTime()));
  }

  /**
   * 〈功能详细描述〉将给定的分钟数转换为小时
   *
   * @since 企业商旅v1.0.0
   */
  public static String convertMinuteToHour(long costMinute) {
    if (costMinute >= 60) {
      long costHour = costMinute / 60;
      long remainMinute = costMinute % 60;
      if (remainMinute == 0) {
        return costHour + "小时";
      } else {
        return costHour + "小时" + remainMinute + "分钟";
      }
    } else {
      return costMinute + "分钟";
    }
  }

  /**
   * 〈功能详细描述〉将给定的分钟数转换为小时
   *
   * @since 企业商旅v1.0.0
   */
  public static String convertMinuteToHour(String costMinute) {
    long costMinuteNum = Long.valueOf(costMinute);
    return convertMinuteToHour(costMinuteNum);

  }

  /**
   * 〈功能详细描述〉通过截取字符串的方式，将给定的yyyy-MM-dd HH:mm:ss.SSS格式的日期转换为精确到分钟的字符串日期
   *
   * @since 企业商旅v1.0.0
   */
  public static String subStrTimeToYyyyMMddHHmm(String date) {
    if (StringUtils.isNotEmpty(date) && date.length() > 16) {
      return date.substring(0, 16);
    } else {
      return date;
    }

  }

  /**
   * 获取本周第一天
   */
  public static String getFirstDateByWeek() {
    Calendar cal = Calendar.getInstance();
    // System.out.println("今天的日期: " +
    // dateParseyyyyMMDD(getyyyy_MM_DD(cal.getTime())));

    int day_of_week = cal.get(Calendar.DAY_OF_WEEK) - 2;
    cal.add(Calendar.DATE, -day_of_week);
    // System.out.println("本周第一天: " + getyyyy_MM_DD(cal.getTime()));

		/*
     * cal.add(Calendar.DATE, 6); System.out.println("本周末: " +
		 * getyyyy_MM_DD(cal.getTime()));
		 */
    return getyyyy_MM_DD(cal.getTime());
  }

  /**
   * 获取本月第一天
   */
  public static String getFirstDateByMonth() {
    Calendar cal = Calendar.getInstance();
    cal.setTime(new Date());
    cal.set(Calendar.DAY_OF_MONTH, 1);
    // System.out.println (new
    // SimpleDateFormat("yyyy-MM-dd").format(cal.getTime()));
    // cal.roll(Calendar.DAY_OF_MONTH, -1);
    System.out.println(new SimpleDateFormat("yyyy-MM-dd").format(cal.getTime()));
    return getyyyy_MM_DD(cal.getTime());
  }

  /**
   * 获取本年第一天
   */
  public static String getFirstDateByYear() {
    Calendar cal = Calendar.getInstance();
    cal.setTime(new Date());
    cal.set(Calendar.DAY_OF_YEAR, 1);
    // System.out.println (new
    // SimpleDateFormat("yyyy-MM-dd").format(cal.getTime()));
    // cal.roll(Calendar.DAY_OF_MONTH, -1);
    System.out.println(new SimpleDateFormat("yyyy-MM-dd").format(cal.getTime()));
    return getyyyy_MM_DD(cal.getTime());
  }

  // ----------------15040603加------------------------------------------
  // 返回当前日期
  public static String DateFunction(Date date) {

    StringBuffer sb = new StringBuffer();
    sb.append(String.valueOf(date.getYear() + 1900) + "-");
    if (String.valueOf(date.getMonth() + 1).length() == 1) {
      sb.append("0");
    }
    sb.append(String.valueOf(date.getMonth() + 1) + "-");
    if (String.valueOf(date.getDate()).length() == 1) {
      sb.append("0");
    }
    sb.append(String.valueOf(date.getDate()));

    return sb.toString();
  }

  public static String get14Time() {
    DateFormat df = new SimpleDateFormat("yyyyMMddHHmmss");
    String c = df.format(new Date());
    return c;
  }

  public static String DateTimeFunction(Date date) {
    StringBuffer sb = new StringBuffer();
    sb.append(DateFunction(date) + " ");
    if (String.valueOf(date.getHours()).length() == 1) {
      sb.append("0");
    }
    sb.append(String.valueOf(date.getHours()) + ":");

    if (String.valueOf(date.getMinutes()).length() == 1) {
      sb.append("0");
    }
    sb.append(String.valueOf(date.getMinutes()) + ":");

    if (String.valueOf(date.getSeconds()).length() == 1) {
      sb.append("0");
    }
    sb.append(String.valueOf(date.getSeconds()));

    return sb.toString();
  }

  /**
   * 根据字符串长度选择返回值得类型 time:13位 毫秒 10位 秒
   */
  public static String formatFrom1970(long time) {
    String oldstr = String.valueOf(time);
    long theMinutes = 0;
    try {
      if (oldstr.length() == 13) {
        theMinutes = time / 1000;
      } else if (oldstr.length() == 10) {
        theMinutes = time;
      }
      // 增加了格林尼治时间的修正
      theMinutes = theMinutes + (8 * 60 * 60);
      theMinutes = DateTimeUtil.ScdChanges("19700101000000", (int) theMinutes);
    } catch (Exception e) {
      e.printStackTrace();
    }
    return String.valueOf(theMinutes);
  }

  public static long getNowTime13() {
    return System.currentTimeMillis();
  }

  /**
   * @description DateTimeFunction 将字符串的时间格式(yyyy-MM-dd hh:mm:ss)转换成14位long型
   */
  public static long DateTimeFunction(String datestString) {
    DateFormat df = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
    long datelong = 0;
    String dateString;
    if (datestString != null && !datestString.equals("")) {
      try {
        Date date = df.parse(datestString);
        dateString = DateTimeUtil.DateTimeFunction(date).replaceAll("-", "").replaceAll(" ", "")
            .replaceAll(":", "");
        datelong = Long.valueOf(dateString);
      } catch (ParseException e) {
        e.printStackTrace();
      }
    }
    return datelong;
  }

  // 根据当前日期返回星期几
  public static String getWeekOfDate(Date dt) {
    String[] weekDays = {"星期日 ", "星期一 ", "星期二 ", "星期三 ", "星期四 ", "星期五 ", "星期六 "};
    Calendar cal = Calendar.getInstance();
    cal.setTime(dt);

    int w = cal.get(Calendar.DAY_OF_WEEK) - 1;
    if (w < 0) {
      w = 0;
    }
    return weekDays[w];

  }

  /**
   * @param yyyy_mm_dd yyyy_mm_dd或yyyy_m_d 将字符串的时间格式(yyyy_mm_dd或yyyy_m_d)换成14位long型
   */
  public static long getTime(String yyyy_mm_dd) {
    long datelong = 0;
    if (yyyy_mm_dd != null && yyyy_mm_dd.trim().length() > 4) {
      if (yyyy_mm_dd.trim().length() == 10) {
        datelong = Long.valueOf(yyyy_mm_dd.replace("-", "") + "000000");
      } else {
        String[] xx = yyyy_mm_dd.split("-");
        StringBuffer sb = new StringBuffer("");
        String dateString;
        for (String st : xx) {
          sb.append((Integer.parseInt(st) > 10) ? st : ("0" + st));
          dateString = sb.toString() + "000000";
          datelong = Long.valueOf(dateString);
        }
      }
    } else {
      return 000000000000;
    }
    return datelong;

  }

  /**
   * 将字符串src中的子字符串fnd全部替换为新子字符串rep.<br>
   * 功能相当于java sdk 1.4的String.replaceAll方法.<br>
   * 不同之处在于查找时不是使用正则表达式而是普通字符串.
   */
  public static String replaceAll(String src, String fnd, String rep) throws Exception {
    if (src == null || src.equals("")) {
      return "";
    }
    String dst = src;
    int idx = dst.indexOf(fnd);
    while (idx >= 0) {
      dst = dst.substring(0, idx) + rep + dst.substring(idx + fnd.length(), dst.length());
      idx = dst.indexOf(fnd, idx + rep.length());
    }
    return dst;
  }

  /**
   * 返回6位或8位或10位或12位或14位字符型日期的YY-MM-DD hh:mm:ss秒形式
   */
  public static String returnStringToRq(String sj) {
    String retrq = "";
    try {
      if (sj == null || sj.length() < 6) {
        return retrq;
      }
      retrq = sj.substring(0, 4) + "-" + sj.substring(4, 6);
      retrq = sj.length() > 6 ? retrq + "-" + sj.substring(6, 8) : retrq;
      retrq = sj.length() > 8 ? retrq + " " + sj.substring(8, 10) : retrq;
      retrq = sj.length() > 10 ? retrq + ":" + sj.substring(10, 12) : retrq;
      retrq = sj.length() > 12 ? retrq + ":" + sj.substring(12, 14) : retrq;

    } catch (Exception e) {
      System.out.println("ProjectUtil.returnStringToRq日期形式转换:" + e);
    }
    return retrq;
  }

  /**
   * 返回6位或8位或10位或12位或14位字符型日期的YY年MM月
   */
  public static String returnStringToRqNY(String sj) {
    String retrq = "";
    try {
      if (sj == null || sj.length() < 4) {
        return retrq;
      }
      retrq = sj.substring(0, 4) + "年" + Integer.valueOf(sj.substring(4, 6)) + "月";
    } catch (Exception e) {
      System.out.println("ProjectUtil.returnStringToRq日期形式转换:" + e);
    }
    return retrq;
  }

  /**
   * 返回6位或8位或10位或12位或14位字符型日期的YY年MM月DD日
   */
  public static String returnStringToRqNYR(String sj) {
    String retrq = "";
    try {
      if (sj == null || sj.length() < 6) {
        return retrq;
      }
      retrq = sj.substring(0, 4) + "年" + sj.substring(4, 6) + "月";
      retrq = sj.length() > 6 ? retrq + sj.substring(6, 8) + "日" : retrq;
    } catch (Exception e) {
      System.out.println("ProjectUtil.returnStringToRq日期形式转换:" + e);
    }
    return retrq;
  }

  /**
   * 返回该日期多少秒后的时间 返回多少秒前的*-1
   *
   * @param rq String
   * @param changs int
   * @return String
   */
  public static long ScdChanges(String rq, int changs) {
    SimpleDateFormat myFormatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    String tmps = "0";

    if (rq == null || rq.equals("")) {
      return 0;
    }
    try {
      Date date = myFormatter
          .parse(String.valueOf(rq).substring(0, 4) + "-" + String.valueOf(rq).substring(4, 6)
              + "-" + String.valueOf(rq).substring(6, 8) + " " + String.valueOf(rq).substring(8, 10)
              + ":"
              + String.valueOf(rq).substring(10, 12) + ":" + String.valueOf(rq).substring(12, 14));

      long Time = (date.getTime() / 1000) + changs;
      date.setTime(Time * 1000);

      tmps = DateTimeUtil.DateTimeFunction(date);
      tmps = DateTimeUtil.replaceAll(tmps, "-", "");
      tmps = DateTimeUtil.replaceAll(tmps, " ", "");
      tmps = DateTimeUtil.replaceAll(tmps, ":", "");
    } catch (Exception ex) {
    } finally {
      return Long.parseLong(tmps);
    }
  }

  public static String DateFormat14(Date date) {

    StringBuffer sb = new StringBuffer();
    sb.append(DateFunction(date).replaceAll("-", ""));
    if (String.valueOf(date.getHours()).length() == 1) {
      sb.append("0");
    }
    sb.append(String.valueOf(date.getHours()));

    if (String.valueOf(date.getMinutes()).length() == 1) {
      sb.append("0");
    }
    sb.append(String.valueOf(date.getMinutes()));

    if (String.valueOf(date.getSeconds()).length() == 1) {
      sb.append("0");
    }
    sb.append(String.valueOf(date.getSeconds()));

    return sb.toString();
  }

  /**
   * 获取现在时间,这个好用
   *
   * @return返回长时间格式 yyyy-MM-dd HH:mm:ss
   */
  public static Date getSqlDate() {
    Date sqlDate = new java.sql.Date(new Date().getTime());
    return sqlDate;
  }

  /**
   * 获取现在时间
   *
   * @return返回长时间格式 yyyy-MM-dd HH:mm:ss
   */
  public static Date getNowDate() {
    Date currentTime = new Date();
    SimpleDateFormat formatter = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
    String dateString = formatter.format(currentTime);
    ParsePosition pos = new ParsePosition(8);
    Date currentTime_2 = formatter.parse(dateString, pos);
    return currentTime_2;
  }

  /**
   * 获取现在时间
   *
   * @return返回短时间格式 yyyy-MM-dd
   */
  public static Date getNowDateShort() {
    Date currentTime = new Date();
    SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
    String dateString = formatter.format(currentTime);
    ParsePosition pos = new ParsePosition(8);
    Date currentTime_2 = formatter.parse(dateString, pos);
    return currentTime_2;
  }

  /**
   * 获取现在时间
   *
   * @return返回字符串格式 yyyy-MM-dd HH:mm:ss
   */
  public static String getStringDate() {
    Date currentTime = new Date();
    SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    String dateString = formatter.format(currentTime);
    return dateString;
  }

  /**
   * 获取现在时间
   *
   * @return 返回短时间字符串格式yyyy-MM-dd
   */
  public static String getStringDateShort() {
    Date currentTime = new Date();
    SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
    String dateString = formatter.format(currentTime);
    return dateString;
  }

  /**
   * 获取时间 小时:分;秒 HH:mm:ss
   */
  public static String getTimeShort() {
    SimpleDateFormat formatter = new SimpleDateFormat("HH:mm:ss");
    Date currentTime = new Date();
    String dateString = formatter.format(currentTime);
    return dateString;
  }

  /**
   * 将长时间格式字符串转换为时间 yyyy-MM-dd HH:mm:ss
   */
  public static Date strToDateLong(String strDate) {
    SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    ParsePosition pos = new ParsePosition(0);
    Date strtodate = formatter.parse(strDate, pos);
    return strtodate;
  }

  /**
   * 将长时间格式时间转换为字符串 yyyy-MM-dd HH:mm:ss
   */
  public static String dateToStrLong(Date dateDate) {
    SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    String dateString = formatter.format(dateDate);
    return dateString;
  }

  /**
   * 将短时间格式时间转换为字符串 yyyy-MM-dd
   */
  public static String dateToStr(Date dateDate) {
    SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
    String dateString = formatter.format(dateDate);
    return dateString;
  }

  /**
   * 将短时间格式字符串转换为时间 yyyy-MM-dd
   */
  public static Date strToDate(String strDate) {
    SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
    ParsePosition pos = new ParsePosition(0);
    Date strtodate = formatter.parse(strDate, pos);
    return strtodate;
  }

  /**
   * 得到现在时间
   */
  public static Date getNow() {
    Date currentTime = new Date();
    return currentTime;
  }

  /**
   * 提取一个月中的最后一天
   */
  public static Date getLastDate(long day) {
    Date date = new Date();
    long date_3_hm = date.getTime() - 3600000 * 34 * day;
    Date date_3_hm_date = new Date(date_3_hm);
    return date_3_hm_date;
  }

  /**
   * 得到现在时间
   *
   * @return 字符串 yyyyMMdd HHmmss
   */
  public static String getStringToday() {
    Date currentTime = new Date();
    SimpleDateFormat formatter = new SimpleDateFormat("yyyyMMdd HHmmss");
    String dateString = formatter.format(currentTime);
    return dateString;
  }

  /**
   * 得到现在小时
   */
  public static String getHour() {
    Date currentTime = new Date();
    SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    String dateString = formatter.format(currentTime);
    String hour;
    hour = dateString.substring(11, 13);
    return hour;
  }

  /**
   * 得到现在小时
   */
  public static String getY_M_D_H_M_S() {
    Date currentTime = new Date();
    SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    String dateString = formatter.format(currentTime);
    return dateString;
  }

  /**
   * 得到现在分钟
   */
  public static String getTime() {
    Date currentTime = new Date();
    SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    String dateString = formatter.format(currentTime);
    String min;
    min = dateString.substring(14, 16);
    return min;
  }

  /**
   * 获取当前yyyy-MM-dd HH:mm:ss 时间
   */
  public static String getYYYY_MM_DD_HH_MM_SS() {
    Date currentTime = new Date();
    SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    String dateString = formatter.format(currentTime);
    return dateString;
  }

  /**
   * 获取当前yyyy-MM-dd HH:mm:ss 时间
   */
  public static String getYYYY_MM_DD_HH_MM_SS(Date time) {
    SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    String dateString = formatter.format(time);
    return dateString;
  }

  /**
   * 根据用户传入的时间表示格式，返回当前时间的格式 如果是yyyyMMdd，注意字母y不能大写。
   *
   * @param sformat yyyyMMddhhmmss
   */
  public static String getUserDate(String sformat) {
    Date currentTime = new Date();
    SimpleDateFormat formatter = new SimpleDateFormat(sformat);
    String dateString = formatter.format(currentTime);
    return dateString;
  }

  /**
   * 二个小时时间间的差值,必须保证二个时间都是"HH:MM"的格式，返回字符型的分钟
   */
  public static String getTwoHour(String st1, String st2) {
    String[] kk = null;
    String[] jj = null;
    kk = st1.split(":");
    jj = st2.split(":");
    if (Integer.parseInt(kk[0]) < Integer.parseInt(jj[0])) {
      return "0";
    } else {
      double y = Double.parseDouble(kk[0]) + Double.parseDouble(kk[1]) / 60;
      double u = Double.parseDouble(jj[0]) + Double.parseDouble(jj[1]) / 60;
      if ((y - u) > 0) {
        return y - u + "";
      } else {
        return "0";
      }
    }
  }

  /**
   * 得到二个日期间的间隔天数
   */
  public static String getTwoDay(String sj1, String sj2) {
    SimpleDateFormat myFormatter = new SimpleDateFormat("yyyy-MM-dd");
    long day = 0;
    try {
      Date date = myFormatter.parse(sj1);
      Date mydate = myFormatter.parse(sj2);
      day = (date.getTime() - mydate.getTime()) / (24 * 60 * 60 * 1000);
    } catch (Exception e) {
      return "";
    }
    return day + "";
  }

  /**
   * 时间前推或后推分钟,其中JJ表示分钟.
   */
  public static String getPreTime(String sj1, String jj) {
    SimpleDateFormat format = new SimpleDateFormat("yyyyMMddHHmmss");
    String mydate1 = "";
    try {
      Date date1 = format.parse(sj1);
      long Time = (date1.getTime() / 1000) + Integer.parseInt(jj) * 60;
      date1.setTime(Time * 1000);
      mydate1 = format.format(date1);
    } catch (Exception e) {
    }
    return mydate1;
  }

  /**
   * 得到一个时间延后或前移几天的时间,nowdate为时间,delay为前移或后延的天数
   */
  public static String getNextDay(String nowdate, String delay) {
    try {
      SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
      String mdate = "";
      Date d = strToDate(nowdate);
      long myTime = (d.getTime() / 1000) + Integer.parseInt(delay) * 24 * 60 * 60;
      d.setTime(myTime * 1000);
      mdate = format.format(d);
      return mdate;
    } catch (Exception e) {
      return "";
    }
  }

  /**
   * 判断是否润年
   */
  public static boolean isLeapYear(String ddate) {
    /**
     * 详细设计： 1.被400整除是闰年，否则： 2.不能被4整除则不是闰年 3.能被4整除同时不能被100整除则是闰年
     * 3.能被4整除同时能被100整除则不是闰年
     */
    Date d = strToDate(ddate);
    GregorianCalendar gc = (GregorianCalendar) Calendar.getInstance();
    gc.setTime(d);
    int year = gc.get(Calendar.YEAR);
    if ((year % 400) == 0) {
      return true;
    } else if ((year % 4) == 0) {
      if ((year % 100) == 0) {
        return false;
      } else {
        return true;
      }
    } else {
      return false;
    }
  }

  /**
   * 返回美国时间格式 26 Apr 2006
   */
  public static String getEDate(String str) {
    SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
    ParsePosition pos = new ParsePosition(0);
    Date strtodate = formatter.parse(str, pos);
    String j = strtodate.toString();
    String[] k = j.split(" ");
    return k[2] + k[1].toUpperCase() + k[5].substring(2, 4);
  }

  /**
   * 获取一个月的最后一天
   */
  public static String getEndDateOfMonth(String dat) {// yyyy-MM-dd
    String str = dat.substring(0, 8);
    String month = dat.substring(5, 7);
    int mon = Integer.parseInt(month);
    if (mon == 1 || mon == 3 || mon == 5 || mon == 7 || mon == 8 || mon == 10 || mon == 12) {
      str += "31";
    } else if (mon == 4 || mon == 6 || mon == 9 || mon == 11) {
      str += "30";
    } else {
      if (isLeapYear(dat)) {
        str += "29";
      } else {
        str += "28";
      }
    }
    return str;
  }

  /**
   * 判断二个时间是否在同一个周
   */
  public static boolean isSameWeekDates(Date date1, Date date2) {
    Calendar cal1 = Calendar.getInstance();
    Calendar cal2 = Calendar.getInstance();
    cal1.setTime(date1);
    cal2.setTime(date2);
    int subYear = cal1.get(Calendar.YEAR) - cal2.get(Calendar.YEAR);
    if (0 == subYear) {
      if (cal1.get(Calendar.WEEK_OF_YEAR) == cal2.get(Calendar.WEEK_OF_YEAR)) {
        return true;
      }
    } else if (1 == subYear && 11 == cal2.get(Calendar.MONTH)) {
      // 如果12月的最后一周横跨来年第一周的话则最后一周即算做来年的第一周
      if (cal1.get(Calendar.WEEK_OF_YEAR) == cal2.get(Calendar.WEEK_OF_YEAR)) {
        return true;
      }
    } else if (-1 == subYear && 11 == cal1.get(Calendar.MONTH)) {
      if (cal1.get(Calendar.WEEK_OF_YEAR) == cal2.get(Calendar.WEEK_OF_YEAR)) {
        return true;
      }
    }
    return false;
  }

  /**
   * 产生周序列,即得到当前时间所在的年度是第几周
   */
  public static String getSeqWeek() {
    Calendar c = Calendar.getInstance(Locale.CHINA);
    String week = Integer.toString(c.get(Calendar.WEEK_OF_YEAR));
    if (week.length() == 1) {
      week = "0" + week;
    }
    String year = Integer.toString(c.get(Calendar.YEAR));
    return year + week;
  }

  /**
   * 获得一个日期所在的周的星期几的日期，如要找出2002年2月3日所在周的星期一是几号
   */
  public static String getWeek(String sdate, String num) {
    // 再转换为时间
    Date dd = strToDate(sdate);
    Calendar c = Calendar.getInstance();
    c.setTime(dd);
    if (num.equals("1")) // 返回星期一所在的日期
    {
      c.set(Calendar.DAY_OF_WEEK, Calendar.MONDAY);
    } else if (num.equals("2")) // 返回星期二所在的日期
    {
      c.set(Calendar.DAY_OF_WEEK, Calendar.TUESDAY);
    } else if (num.equals("3")) // 返回星期三所在的日期
    {
      c.set(Calendar.DAY_OF_WEEK, Calendar.WEDNESDAY);
    } else if (num.equals("4")) // 返回星期四所在的日期
    {
      c.set(Calendar.DAY_OF_WEEK, Calendar.THURSDAY);
    } else if (num.equals("5")) // 返回星期五所在的日期
    {
      c.set(Calendar.DAY_OF_WEEK, Calendar.FRIDAY);
    } else if (num.equals("6")) // 返回星期六所在的日期
    {
      c.set(Calendar.DAY_OF_WEEK, Calendar.SATURDAY);
    } else if (num.equals("0")) // 返回星期日所在的日期
    {
      c.set(Calendar.DAY_OF_WEEK, Calendar.SUNDAY);
    }
    return new SimpleDateFormat("yyyy-MM-dd").format(c.getTime());
  }

  /**
   * 根据一个日期，返回是星期几的字符串
   */
  public static String getWeek(String sdate) {
    // 再转换为时间
    Date date = strToDate(sdate);
    Calendar c = Calendar.getInstance();
    c.setTime(date);
    // int hour=c.get(Calendar.DAY_OF_WEEK);
    // hour中存的就是星期几了，其范围 1~7
    // 1=星期日 7=星期六，其他类推
    return new SimpleDateFormat("EEEE").format(c.getTime());
  }

  public static String getWeekStr(String sdate) {
    String str = "";
    str = getWeek(sdate);
    if ("1".equals(str)) {
      str = "星期日";
    } else if ("2".equals(str)) {
      str = "星期一";
    } else if ("3".equals(str)) {
      str = "星期二";
    } else if ("4".equals(str)) {
      str = "星期三";
    } else if ("5".equals(str)) {
      str = "星期四";
    } else if ("6".equals(str)) {
      str = "星期五";
    } else if ("7".equals(str)) {
      str = "星期六";
    }
    return str;
  }

  /**
   * 两个时间之间的天数
   */
  public static long getDays(String date1, String date2) {
    if (date1 == null || date1.equals("")) {
      return 0;
    }
    if (date2 == null || date2.equals("")) {
      return 0;
    }
    // 转换为标准时间
    SimpleDateFormat myFormatter = new SimpleDateFormat("yyyy-MM-dd");
    Date date = null;
    Date mydate = null;
    try {
      date = myFormatter.parse(date1);
      mydate = myFormatter.parse(date2);
    } catch (Exception e) {
    }
    long day = (date.getTime() - mydate.getTime()) / (24 * 60 * 60 * 1000);
    return day;
  }

  /**
   * 形成如下的日历 ， 根据传入的一个时间返回一个结构 星期日 星期一 星期二 星期三 星期四 星期五 星期六 下面是当月的各个时间
   * 此函数返回该日历第一行星期日所在的日期
   */
  public static String getNowMonth(String sdate) {
    // 取该时间所在月的一号
    sdate = sdate.substring(0, 8) + "01";
    // 得到这个月的1号是星期几
    Date date = strToDate(sdate);
    Calendar c = Calendar.getInstance();
    c.setTime(date);
    int u = c.get(Calendar.DAY_OF_WEEK);
    String newday = getNextDay(sdate, (1 - u) + "");
    return newday;
  }

  /**
   * 取得数据库主键 生成格式为yyyymmddhhmmss+k位随机数
   *
   * @param k 表示是取几位随机数，可以自己定
   */
  public static String getNo(int k) {
    return getUserDate("yyyyMMddhhmmss") + getRandom(k);
  }

  /**
   * 返回一个随机数
   */
  public static String getRandom(int i) {
    Random jjj = new Random();
    // int suiJiShu = jjj.nextInt(9);
    if (i == 0) {
      return "";
    }
    String jj = "";
    for (int k = 0; k < i; k++) {
      jj = jj + jjj.nextInt(9);
    }
    return jj;
  }

  /**
   * @param date
   */
  public static boolean RightDate(String date) {
    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
    ;
    if (date == null) {
      return false;
    }
    if (date.length() > 10) {
      sdf = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
    } else {
      sdf = new SimpleDateFormat("yyyy-MM-dd");
    }
    try {
      sdf.parse(date);
    } catch (ParseException pe) {
      return false;
    }
    return true;
  }

  public static long[] getXiangJian(String alld1, String alld2) throws Exception {
    long[] hms = new long[3];
    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    Date d1 = sdf.parse(alld1);
    Date d2 = sdf.parse(alld2);
    long diff = d1.getTime() - d2.getTime();// 这样得到的差值是微秒级别
    long days = diff / (1000 * 60 * 60 * 24);
    long hours = (diff - days * (1000 * 60 * 60 * 24)) / (1000 * 60 * 60);
    long minutes = (diff - days * (1000 * 60 * 60 * 24) - hours * (1000 * 60 * 60)) / (1000 * 60);
    hms[0] = days;
    hms[1] = hours;
    hms[2] = minutes;
    return hms;
  }

  public static XMLGregorianCalendar convertToXMLGregorianCalendar(Date date) {

    GregorianCalendar cal = new GregorianCalendar();
    cal.setTime(date);
    XMLGregorianCalendar gc = null;
    try {
      gc = DatatypeFactory.newInstance().newXMLGregorianCalendar(cal);
    } catch (Exception e) {

      e.printStackTrace();
    }
    return gc;
  }

  public static Date convertToDate(XMLGregorianCalendar cal) throws Exception {
    GregorianCalendar ca = cal.toGregorianCalendar();
    return ca.getTime();
  }

  // 判断时间是否过期
  public static int passDate(Date start, Date end) {
    boolean isExpired = start.after(end);
    // try {
    // Date now = new Date();
    // if (start.compareTo(now) < 0) {
    // if (end.compareTo(now) > 0) {
    // return 0;
    // } else {
    // return 1;
    // }
    // } else {
    // return 1;
    // }
    // } catch (Exception e) {
    // System.out.println("出现异常,可能时间有问题!");
    // return 1;
    // }

    return isExpired ? 1 : 0;
  }

  public static String formatDate(Date date) {
    String result = "";
    DateTime dt1 = new DateTime();
    DateTime dt2 = new DateTime(date);
    Period p = new Period(dt2, dt1, PeriodType.minutes());
    int minutes = p.getMinutes();
    if (minutes <= 10) {
      result = minutes + "分钟前";
    } else if (minutes > 10 && minutes <= 30) {
      result = "10分钟前";
    } else if (minutes > 30 && minutes <= 60) {
      result = "30分钟前";
    } else {
      p = new Period(dt2, dt1, PeriodType.hours());
      int hours = p.getHours();
      if (hours <= 24) {
        result = hours + "小时前";
      } else {
        result = DateUtil.format(date, DateUtil.DATE_FORMAT);
      }
    }
    return result;
  }

//  public static void main(String[] args) throws ParseException {
//    Date d1 = DateUtil.convertStrToDate("2016-11-02 10:33:40");
//    Date d2 = DateUtil.convertStrToDate("2016-11-02 10:33:40");
//    System.out.println(passDate(d1, d2));
//  }

}
